/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useRef } from 'react';
import { EditableProTable } from '@ant-design/pro-table';

export default ({
  columns,
  dataSource,
  title,
  setDataSource,
  editableKeys,
  setEditableRowKeys,
  extra,
}: any) => {
  useEffect(() => {
    setEditableRowKeys(dataSource.map((v) => v.id));
  }, [dataSource]);

  const data = { id: Date.now(), key: '', value: '' };
  const actionRef = useRef();
  return (
    <EditableProTable
      actionRef={actionRef}
      headerTitle={title}
      columns={columns}
      rowKey='id'
      value={dataSource}
      onChange={setDataSource}
      recordCreatorProps={false}
      editable={{
        type: 'multiple',
        editableKeys,
        actionRender: (row, config, defaultDoms) => {
          return [defaultDoms.delete];
        },
        onValuesChange: (record, recordList) => {
          if (extra) {
            extra(recordList);
          }
          if (record && record.key) {
            if (recordList[recordList.length - 1].key == record.key) {
              recordList.push(data);
            }
          }
          setDataSource(recordList);
        },
        onChange: setEditableRowKeys,
      }}
    />
  );
};
